<template>
  <div class="h-full flex flex-col">
    <a-card>
      <div slot="title" class="title">
        <a-space>
          <div class="ty"></div>
          {{ $t('app.setting.production.hint') }}
        </a-space>
        <a-button type="primary" @click="exportFile">{{ $t('user.password.strength.low222333') }}</a-button>
      </div>
      <a-row>
        <a-col :span="10">
          <div>
            <p style="display: inline-block;padding-top: 4px;">{{ $t('app.setting.themecolor.dust.selecttype') }}：</p>
            <a-input-search :placeholder="$t('menu.form.basic-form')" enter-button style="width: 200px"
                            @search="onSearch" @change="onChange"/>
          </div>
          <a-tree :tree-data="treeData" :default-expand-all="true" show-line show-icon @select="onSelect"
                  :expandedKeys="expandedKeys" @expand="onExpand" v-if="treeData.length>0" style="height: 600px; overflow: auto;" >
            <template #title="{ Id, SourceName, SourceSuperior, level, nodeStr ,SourceNameEn}">
              <div class="flex flex-row  items-center py-2">
                <div class="truncate pr-2">
                  <div class="inline-block min-w-[132px] h-[32px] leading-[32px] text-center" @click="treePut(Id,level)" 
                    :style="{ 'background-color': selectedNodeId === Id ? '#8adef8' : `rgba(36, 89, 229,${level == 1 ? 1 : 1 - (level * 0.2)} `, color: level < 3 ? '#fff' : '#2459E5', }">
                    {{ isLang ? SourceName : SourceNameEn }}
                  </div>
                </div>
              </div>
            </template>
          </a-tree>
        </a-col>
        <a-col :span="14">
          <!-- 主列表 -->
          <a-table ref="table" size="middle" class="h-full overflow-x-auto" :dataSource="listData"
                   :loading="loading" :rowKey="record => record.Id">
            <a-table-column key="SourceChildName" data-index="SourceChildName" :title="$t('app.setting.themecolor.ii')"
                            width="150">
              <template slot-scope="text, record">
                <span>{{ isLang ? record.SourceChildName : record.SourceChildNameEn }}</span>
              </template>
              <!-- <span slot="title" >{{ $t('app.setting.themecolor.ii') }}</span> -->
            </a-table-column>
            <a-table-column key="SourceSensitivityLevel" data-index="SourceSensitivityLevel" width="150">
              <span slot="title">{{ $t('app.setting.themecolor.pp') }}</span>
            </a-table-column>
            <a-table-column key="SourceDataLevel" data-index="SourceDataLevel" width="150">
              <span slot="title">{{ $t('app.setting.themecolor.oo') }}</span>
            </a-table-column>
            <a-table-column key="SourceProtectionLevel" data-index="SourceProtectionLevel" width="150">
              <span slot="title">{{ $t('app.setting.themecolor.qq') }}</span>
            </a-table-column>
          </a-table>
        </a-col>
      </a-row>

      <!-- 抽屉组件  ref绑定save  succeed绑定初始化的 init事件  -->
      <createEdit ref="createEdit" @succeed="init"/>
    </a-card>
    <div class="big-box" v-if="ifLoading">
      <a-spin />
    </div>
  </div>
</template>

<script>
import {sourceTree} from '@/api/ytdg'
import CreateEdit from '../classification/components/createEdit'
import {listToTree} from '@/utils/util'
import {sourceDelete, sourceFind} from '@/api/dcc'
import {i18n, setI18nLanguage} from '@/locales/index'
import axios from 'axios'
import storage from "store";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import moment from "moment"

export default {
  components: {
    CreateEdit
  },
  data() {
    return {
      // expandedKey: [], // 默认展开的节点的 key 值
      expandedKeys: [],
      switchStatus: true, // 初始状态为打开
      switchColor: '#1890ff', // 初始状态下的开关颜色
      defaultExpandAll: false,
      checked: true,
      loading: false,
      types: '',
      treeData: [],
      treeId: '',
      mateData: [],
      listData: [],
      visible: false,
      father: false,
      isLang: true,
      columns: [
        {
          title: '数据项',
          className: 'min-w-90p',
          dataIndex: 'SourceChildName',
          align: 'center',
        },
        {
          title: '敏感性分级',
          className: 'min-w-90p',
          dataIndex: 'SourceSensitivityLevel',
          align: 'center',
        },
        {
          title: '数据等级',
          className: 'min-w-90p',
          dataIndex: 'SourceDataLevel',
          align: 'center',
        },
        {
          title: '保护等级',
          className: 'min-w-90p',
          dataIndex: 'SourceProtectionLevel',
          align: 'center',
        }
      ],
      ifLoading: false,
      selectedNodeId: null,
      selectedNode: null,}
    },
  created() {
    this.init()
  },
  mounted() {
    let that = this;
    window.addEventListener('setItemEvent', function (e) {
      if (e.key == 'lang') {
        let lang = JSON.parse(e.value)
        console.log(lang);
        if (lang == 'zh-EN') {
          that.isLang = false;
        } else {
          that.isLang = true
        }
      }
    })
  },
  methods: {
    onSelect(keys, event) {
      event.node.onExpand()
    },
    //展开tree
    onExpand(expandedKeys, {expanded: bool, node}) {
      console.log('expandedKeys', expandedKeys);
      console.log('node', node);
      console.log('bool',bool);
      this.expandedKeys = expandedKeys
    },
    //搜索发生变化时
    onChange(e) {
      console.log(e);
      if (e.data == null) {
        this.init();
      }
    },
    //展开所有数据
    expandedKeysOpenAll(data) {
      if (!data || data.length === 0) return; 
      // console.log('data', data);
      let arr = Array.from(data);
      arr.forEach(item => {
        this.expandedKeys.push(item.key);
        if (item.children && item.children.length > 0) {
          this.expandedKeysOpen(item.children)
        }
      })
    },
    //展开搜索的数据
    async expandedKeysOpen(data, value) {
      console.log('this.data', data, value)
      let arr = Array.from(data);
      console.log('arr', arr);
      arr.some(item => {
        if (item.SourceName.indexOf(value) != -1) {
          if (!this.expandedKeys.includes(item.key)) {
            this.expandedKeys.push(item.key)
          }
          if (item.children && item.children.length > 0) {
            this.expandedKeysOpen(item.children, value)
          }
        } else {
          if (item.children && item.children.length > 0) {
            if (!this.expandedKeys.includes(item.key)) {
              this.expandedKeys.push(item.key)
            }
            this.expandedKeysOpen(item.children, value)
          }
        }
      })
      console.log('this.expandedKeys', this.expandedKeys);
    },
    // 搜索
    async onSearch(value) {
      console.log(value);
      try {
        if (this.isLang) {
          const {data} = await sourceTree({types: 1, SourceName: value})
          data.some(item => {
            item.key = item.Id
          })
          const listData = listToTree([...data], {
            id: 'Id',
            pid: 'SourceSuperior',
            branch: 'children',
            name: 'SourceName',
          })
          this.treeData = listData;
          this.expandedKeysOpen(this.treeData, value)
        } else {
          const {data} = await sourceTree({types: 2, SourceNameEn: value})
          data.some(item => {
            item.key = item.Id
          })
          const listData = listToTree([...data], {
            id: 'Id',
            pid: 'SourceSuperior',
            branch: 'children',
            name: 'SourceName',
          })
          this.treeData = listData
          this.expandedKeysOpen(this.treeData, value)
        }
      } catch (error) {
        this.$message.error(error)
        console.log(error);
      } finally {
        this.loading = false
      }
    },
    async treePut(id,level) {
      console.log('level,',level);
      const {data} = await sourceFind({id: id})
      console.log('data-------99999', data);
      this.listData = data;
      if (level === 4) {
        this.selectedNodeId = id;
      } else {
        this.selectedNodeId = null;
      }
    },
  
    control(val1) {
      this.father = val1
      this.init()
    },
    async init() {
      this.loading = true
      try {
        let lang = localStorage.getItem('lang');
        this.treeId = ''
        if (lang == '"zh-CN"') {
          this.isLang = true
          const {data} = await sourceTree({types: 1})
          data.some(item => {
            item.key = item.Id
          })
          const listData = listToTree([...data], {
            id: 'Id',
            pid: 'SourceSuperior',
            branch: 'children',
            name: 'SourceName',
          })
          this.treeData = listData
          this.expandedKeysOpenAll()
        } else {
          this.isLang = false
          const {data} = await sourceTree({types: 1})
          data.some(item => {
            item.key = item.Id
          })
          const listData = listToTree([...data], {
            id: 'Id',
            pid: 'SourceSuperior',
            branch: 'children',
            name: 'SourceNameEn',
          })
          this.treeData = listData
          this.expandedKeysOpenAll()
        }
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    //  新增一级分类
    showModal() {
      this.$refs.createEdit.open()
    },
    /**
     * 创建
     * @param {*} key
     */
    create(parentData) {
      this.$refs.createEdit.insert(parentData)
    },
    /**
     * 修改
     * @param {*}
     */
    edit(data) {
      this.$refs.createEdit.edit(data)
    },
    /**
     * 删除
     * @param {*} id
     */
    async del(id) {
      console.log(id);
      const _this = this
      this.$confirm({
        title: this.$t('user.verification-code.required111566110577132'),
        content: this.$t('This operation is irreversible. Are you sure you want to delete it?'),
        okText: this.$t('app.setting.weakmode'),
        okType: 'danger',
        cancelText: this.$t('user.email.required11'),
        async onOk() {
          try {
            await sourceDelete({id})
            _this.$message.success(_this.$t('user.verification-code.required111566110577133'))
            _this.init()
          } catch (error) {
            _this.$message.error(error)
          }
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    // 导出文件
    async exportFile() {
      this.ifLoading = true
      const data = await axios({
        url: `${process.env.VUE_APP_BASE_API}/v1/childdata/export`,
        method: 'post',
        headers: {
          token: storage.get(ACCESS_TOKEN),
          tokens:storage.get("bmwToken") || "",
        },
        responseType: 'arraybuffer',
      })
      this.ifLoading = false
      if (data.status == 200) {
        const url = window.URL.createObjectURL(
          new Blob([data.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })
        )
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', `${moment().format('L')}.xls`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } else {
        this.$message.error(this.$t('user.verification-code.required111566110577327'))
      }
    }
  },
}
</script>
<style lang="less" scoped>
.title {
  display: flex;
  justify-content: space-between;
}
:deep(.ant-tree li ul) {
  padding-left: 50px !important;
}

:deep(.ant-tree li .ant-tree-node-content-wrapper) {
  width: calc(100% - 24px);
  height: 50px;

  &:hover {
    background: none;

    .action {
      display: flex;
    }
  }
}

:deep(.ant-tree li span.ant-tree-switcher) {
  height: 40px;
  padding-top: 12px;
  padding-bottom: 8px;
}

:deep(.ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected) {
  background: transparent;
}

:deep(.ant-tree.ant-tree-show-line li:not(:last-child)::before) {
  border-left: 1px solid #2459E5;
}

:deep(.ant-tree-switcher) {

  font-size: 20px;
}

:deep(.ant-tree-switcher-line-icon) {
  color: #2459E5;
}

:deep(.ant-tree.ant-tree-show-line li:not(:last-child)::before) {
  top: 18px;
}

// 关闭样式
:deep(.ant-tree-switcher_close) {
  background: url(~@/assets/icons/close.svg) no-repeat center !important;

  i {
    display: none;
  }
}

//打开样式
:deep(.ant-tree-switcher_open) {
  background: url(~@/assets/icons/open.svg) no-repeat center !important;

  i {
    display: none;
  }
}

:deep(.ant-tree li span.ant-tree-switcher.ant-tree-switcher-noop) {
  position: relative;
  // background: url(~@/assets/icons/open.svg) no-repeat center !important;

  &::before {
    content: ' ';
    background: #fff;
    position: absolute;
    height: 30px;
    width: 28px;
    top: 40px;
    left: 0;
  }

  i {
    display: none;
  }
}
.big-box {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999999;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>